package cn.csq.netty.nio;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * 将文本内容写入到文件中
 */
public class NIOFileChannel01 {
    public static void main(String[] args) throws  Exception{

        String str = "NIO File Channel Test";

        //创建一个输出流
        FileOutputStream fileOutputStream = new FileOutputStream("/Users/csq/Desktop/study/code/netty-study/src/main/resources/fileChannel.txt");

        //通过文件输出流获取对应的fileChannel
        FileChannel fileChannel = fileOutputStream.getChannel();


        //创建一个缓存区 将文本内容写入到缓冲区中
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        byteBuffer.put(str.getBytes(StandardCharsets.UTF_8));

        //对byteBuffer进行flip 应该在上面操作中写入流数据 position到后面去了，这里需要翻转到0 写入到fileChannel中
        byteBuffer.flip();

        //把buffer数据写入到通道中
        fileChannel.write(byteBuffer);
        fileOutputStream.close();


    }
}
